package com.wynn.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wynn.dao.EquipDao;
import com.wynn.pojo.EquipError;
import com.wynn.pojo.Equipment;

import com.wynn.pojo.ProductLine;
import com.wynn.pojo.Result;
import com.wynn.service.EquipmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Transactional
@RestController
@RequestMapping("equip")
public class EquipmentServiceImpl implements EquipmentService {

    @Autowired
    private EquipDao equipDao;
    @Autowired
    private RedisTemplate redisTemplate;

    //首页查询设备概况
    @Override
    @GetMapping("selectEquipCondition")
    public Result selectEquipCondition(){
        Result result = new Result();
        HashMap<String, Integer> equipCondition = new HashMap<String, Integer>();
        try{
            //设备的三种状态
            String[] str={"bad","wait","run"};
            //根据状态查询设备的数量
            for (int i = 0; i < 3; i++) {
                int num = equipDao.findNumByStatus(i-1);
                equipCondition.put(str[i],num);
                result.setCode("200");
                result.setData(equipCondition);
            }
            log.info("统计设备状态");
        }catch (Exception e){
            log.warn("设备状态查询失败");
            result.setCode("503");
            result.setMessage("设备状态查询失败");
        }

        return result;
    }

    //查询全部设备表
    @Override
    @GetMapping("selectAll")
    public Result selectAll(){
        Result result = new Result();
        try {
            List<Equipment> equipmentList = equipDao.findAll();


            result.setData(equipmentList);
            result.setCode("200");
            log.info("查询设备列表");
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("查询设备失败");
            log.warn("查询设备列表失败");
        }
        return result;
    }

    //添加设备
    @Override
    @PostMapping("add")
    public Result add(@RequestBody Equipment equipment){
        redisTemplate.delete("equipmentList");
        redisTemplate.delete("equipmentNames");
        Result result = new Result();
        try {
            equipDao.add(equipment);
            result.setCode("200");
            result.setMessage("添加设备成功");
            log.info("添加设备"+equipment.getEquipName());
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("添加设备失败");
            log.warn("添加设备"+equipment.getEquipName()+"失败");
        }
        return result;
    }

    //删除设备
    @Override
    @GetMapping("delete")
    public Result delete(int id){
        redisTemplate.delete("equipmentList");
        redisTemplate.delete("equipmentNames");
        Result result = new Result();
        try{
            equipDao.delete(id);
            result.setCode("200");
            result.setMessage("设备删除成功");
            log.info("删除设备"+id);
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("删除设备失败");
            log.warn("添加设备"+id+"失败");
        }
        return result;
    }

    //修改设备
    @Override
    @PostMapping("edit")
    public Result edit(@RequestBody Equipment equipment){
        redisTemplate.delete("equipmentList");
        redisTemplate.delete("equipmentNames");
        Result result = new Result();

        try {
            equipDao.edit(equipment);
            result.setCode("200");
            log.info("修改设备"+equipment.getEquipName());
        }catch (Exception e){
            result.setCode("503");
            log.warn("修改设备"+equipment.getEquipName()+"失败");
        }

        return result;
    }

    //查询设备名称列表,用于下拉框
    @Override
    @GetMapping("getEquipName")
    public Result getEquipName(){
        Result result = new Result();

        try {

            List<String> equipmentNames = null;
            Boolean flag = redisTemplate.hasKey("equipmentNames" );
            if (flag) {
                // 优先从缓存获取
                equipmentNames = redisTemplate.opsForList().range("equipmentNames", 0, -1);
            }else {
                equipmentNames = equipDao.getEquipName();
                redisTemplate.opsForList().rightPushAll("equipmentNames", equipmentNames);
            }

            result.setCode("200");
            result.setData(equipmentNames);
            log.info("查询设备名称");
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("查询设备名称失败");
            log.warn("查询设备名称失败");
        }

        return result;
    }

    //按条件查询
    @Override
    @GetMapping("search")
    public Result search(String name,String line,String equipNum) {
        Result result = new Result();
        try {
            //若name为空,则设为null用查询数据库时的条件判断
            if (name.equals("")){
                name=null;
            }
            if (equipNum.equals("")){
                equipNum=null;
            }
            //若产线id为空,则设为0用查询数据库时的条件判断
            int lineId;
            if (line.equals("")){
                lineId=0;
            }else {
                lineId=Integer.parseInt(line);
            }
            List<Equipment> equipmentList =  equipDao.search(name,lineId,equipNum);
            result.setData(equipmentList);
            result.setCode("200");
            log.info("条件搜素设备");
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("搜索失败");
            log.warn("条件搜素设备失败");
        }

        return result;
    }

    //查询故障设备记录
    @Override
    @GetMapping("selectEquipError")
    public Result selectEquipError() {
        Result result = new Result();
        try{
            List<EquipError> equipErrors = equipDao.selectEquipError();
            result.setData(equipErrors);
            result.setCode("200");
            log.info("查询故障记录");
        }catch (Exception e){
            result.setCode("503");
            result.setMessage("查询故障记录失败");
            log.warn("查询故障记录失败");
        }
        return result;
    }

    //查询当前处于正常状态的设备,用于选择故障设备的下拉框
    @Override
    @GetMapping("selectEquipAva")
    public Result selectEquipAva() {
        Result result = new Result();
        List<Equipment> equipmentList = equipDao.selectEquipAva();
        result.setData(equipmentList);
        log.info("查询正常设备");
        return result;
    }

    //添加故障设备记录
    @Override
    @PostMapping("addEquipError")
    public void addEquipError(@RequestBody EquipError equipError) {

        //设置设备故障记录时间
        equipError.setCreateDate(new Date());
        //通过商品编号查询产线
        ProductLine productLine = equipDao.findPLidByEquip(equipError.getEquipment().getEquipNum());
        equipError.setProductLine(productLine);
        //添加故障记录
        equipDao.addEquipError(equipError);

        //更新设备的状态
        Equipment equipment = equipError.getEquipment();
        equipment.setStatus(-1);
        equipDao.recoverEquip(equipment);

    }

    @Override
    @PostMapping("editEquipError")
    public void editEquipError(@RequestBody Map<String,Object> editMap) {

        Object equipErrorData =  editMap.get("equipError");
        Object editEquipData = editMap.get("editEquip");

        //将object转化为具体对象
        ObjectMapper mapper = new ObjectMapper();
        EquipError equipError = mapper.convertValue(equipErrorData,EquipError.class);
        Equipment editEquip = mapper.convertValue(editEquipData,Equipment.class);


        //设置设备故障记录时间
        equipError.setCreateDate(new Date());
        //通过商品编号查询产线
        ProductLine productLine = equipDao.findPLidByEquip(equipError.getEquipment().getEquipNum());
        equipError.setProductLine(productLine);
        //修改故障记录
        equipDao.editEquipError(equipError);

        //恢复设备可用状态
        equipDao.recoverEquip(editEquip);

        //更新设备故障状态
        Equipment equipment = equipError.getEquipment();
        equipment.setStatus(-1);
        equipDao.recoverEquip(equipment);

    }

    @Override
    @GetMapping("delEquipError")
    public void delEquipError(int id) {
        equipDao.delEquipError(id);
    }

    @Override
    @PostMapping("fixEquipError")
    public void fixEquipError(@RequestBody EquipError equipError) {
        equipError.setStatus("0");
        equipDao.editEquipError(equipError);
    }

    @Override
    @PostMapping("checkEquipError")
    public void checkEquipError(@RequestBody EquipError equipError) {
        equipError.setStatus("1");
        equipDao.editEquipError(equipError);

        //更新设备故障状态
        Equipment equipment = equipError.getEquipment();
        equipment.setStatus(0);
        equipDao.recoverEquip(equipment);
    }

    @Override
    @GetMapping("equipErrorSearch")
    public Result equipErrorSearch(String equipNum, String productLine, String status) {
        Result result = new Result();
        if (equipNum.equals("")){
            equipNum=null;
        }
        if (status.equals("")){
            status=null;
        }
        //若产线id为空,则设为0用查询数据库时的条件判断
        int lineId;
        if (productLine.equals("")){
            lineId=0;
        }else {
            lineId=Integer.parseInt(productLine);
        }
        //条件搜索设备故障记录
        List<EquipError> equipErrors =  equipDao.equipErrorSearch(equipNum,lineId,status);
        result.setData(equipErrors);
        return result;
    }
}
